package cn.topcodes.tcsf.admin.web.controller;

import cn.topcodes.tcsf.admin.commons.api.domain.ApiResponseEntity;
import cn.topcodes.tcsf.admin.commons.api.security.ShiroUtil;
import cn.topcodes.tcsf.admin.domain.entity.SysUser;
import cn.topcodes.tcsf.admin.service.ops.RespCheckVersion;
import cn.topcodes.tcsf.admin.service.ops.SysUpgradeService;
import cn.topcodes.tcsf.admin.service.org.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;


@Controller
@RequestMapping("/admin")
public class VersionController {

	@Autowired
	private SysUpgradeService upgradeService;

	@Autowired
	private SysUserService sysUserService;

	/**
	 * 版本信息
	 * @return
	 */
	@RequestMapping(value = "version",method = RequestMethod.GET)
	public String version() {
		return "admin/version";
	}

	@ResponseBody
	@GetMapping("check-version")
	public ApiResponseEntity checkVersion() {
		RespCheckVersion respCheckVersion = upgradeService.checkVersion();
		if(respCheckVersion == null) {
			return ApiResponseEntity.buildFailed();
		}
		return ApiResponseEntity.buildOK(respCheckVersion);
	}

	@ResponseBody
	@PostMapping("upgrade")
	public ApiResponseEntity upgrade(
			@RequestParam String version,
			@RequestParam String url,
			@RequestParam String password
	) {
		Long sysUserId = ShiroUtil.getUserId();
		SysUser sysUser = sysUserService.findOne(sysUserId);
		if(sysUserService.isPwdEqual(password, sysUser)) {
			upgradeService.upgrade(version, url);
			return ApiResponseEntity.buildOK();
		}else {
			return ApiResponseEntity.buildFailed("密码错误");
		}
	}
}
